<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item label="客户名称:" prop="key">
        <el-input v-model="dataForm.key" placeholder="客户名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="时间范围:" prop="dateRange">
        <el-date-picker
          v-model="dataForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button type="success" plain @click="_exportCSV()">导出</el-button>
        <el-button type="info" @click="clientReportVisible = true">配置导出字段</el-button>
        <el-button @click="printContent">打印</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      stripe
      id="clientReportDetailTable"
      :summary-method="getSummaries"
      show-summary
      v-loading="dataListLoading"
      :span-method="arraySpanMethod"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="index"
        :index="indexMethod"
        width="50"
        header-align="center"
        align="center"
        label="序号">
      </el-table-column>
      <el-table-column
        prop="receiptId"
        header-align="center"
        align="center"
        v-if='false'
        label="销售订单">
      </el-table-column>
      <el-table-column
        prop="clientName"
        header-align="center"
        align="center"
        label="客户名称">
      </el-table-column>
      <el-table-column
        prop="fundsOrderDate"
        header-align="center"
        align="center"
        label="结算时间">
      </el-table-column>
      <el-table-column
        prop="accountName"
        header-align="center"
        align="center"
        label="账户名称">
      </el-table-column>
      <el-table-column
        prop="receiptAmount"
        header-align="center"
        align="center"
        label="收款金额">
      </el-table-column>
      <el-table-column
        prop="saleOrder"
        header-align="center"
        align="center"
        label="销售单">
      </el-table-column>
      <el-table-column
        prop="saleAmount"
        header-align="center"
        align="center"
        label="销售总金额">
      </el-table-column>
      <el-table-column
        prop="writtenOffAmount"
        header-align="center"
        align="center"
        label="已销货金额">
      </el-table-column>
      <el-table-column
        prop="thisWrittenOffAmount"
        header-align="center"
        align="center"
        label="本次销货金额">
      </el-table-column>
      <el-table-column
        prop="remainAmount"
        header-align="center"
        align="center"
        label="剩余金额">
      </el-table-column>
      <el-table-column
        prop="thisWrittenOffNum"
        header-align="center"
        align="center"
        label="本次销贷次数">
      </el-table-column>
      <el-table-column
        prop="writtenOffNum"
        header-align="center"
        align="center"
        label="共计销贷次数">
      </el-table-column>
      <el-table-column
        prop="remark"
        header-align="center"
        align="center"
        label="备注">
      </el-table-column>
    </el-table>
    <el-dialog
      title="提示"
      :visible.sync="clientReportVisible"
      width="30%"
    >
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      <div style="margin: 15px 0;"></div>
      <el-checkbox-group v-model="checkedDetails" @change="handleCheckedCitiesChange">
        <el-checkbox v-for="city in reportDetails" :label="city" :key="city">{{city}}</el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
    <el-button @click="clientReportVisible = false">取 消</el-button>
    <el-button type="primary" @click=handleTitle>确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
  // import AddOrUpdate from './clientreportdetailvo-add-or-update'
  const reportDetails = ['客户名称', '结算时间', '账户名称', '收款金额', '销售单', '销售总金额', '已销货金额', '本次销货金额', '剩余金额', '本次销贷次数', '共计销贷次数', '备注']
  const alertReportDetailName = {
    '客户名称': 'clientName',
    '结算时间': 'fundsOrderDate',
    '账户名称': 'accountName',
    '收款金额': 'receiptAmount',
    '销售单': 'saleOrder',
    '销售总金额': 'saleAmount',
    '已销货金额': 'writtenOffAmount',
    '本次销货金额': 'thisWrittenOffAmount',
    '剩余金额': 'remainAmount',
    '本次销贷次数': 'thisWrittenOffNum',
    '共计销贷次数': 'writtenOffNum',
    '备注': 'remark'
  }
  export default {
    data () {
      return {
        dataForm: {
          key: '',
          dateRange: ''
        },
        beginDate: '',
        endDate: '',
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        firstIndex: '',
        indexInfoList: [],
        checkAll: true,
        checkedDetails: ['客户名称', '结算时间', '账户名称', '收款金额', '销售单', '销售总金额', '已销货金额', '本次销货金额', '剩余金额', '本次销贷次数', '共计销贷次数', '备注'],
        reportDetails: reportDetails,
        isIndeterminate: true,
        clientReportVisible: false,
        titleList: '客户名称,结算时间,账户名称,收款金额,销售单,销售总金额,已销货金额,本次销货金额,剩余金额,本次销贷次数,共计销贷次数,备注',
        keyList: 'clientName,fundsOrderDate,accountName,receiptAmount,saleOrder,saleAmount,writtenOffAmount,thisWrittenOffAmount,remainAmount,thisWrittenOffNum,writtenOffNum,remark'
      }
    },
    // components: {
    //   AddOrUpdate
    // },
    activated () {
      this.getDataList()
    },
    methods: {
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/funds/clientreportdetailvo/listAll'),
          method: 'post',
          params: this.$http.adornParams({
            // 'page': this.pageIndex,
            // 'limit': this.pageSize,
            'key': this.dataForm.key,
            'beginDate': this.dataForm.dateRange === null ? '' : this.dataForm.dateRange[0],
            'endDate': this.dataForm.dateRange === null ? '' : this.dataForm.dateRange[1]
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page

            // 获取每个类目下的条数
            let arr = []
            this.dataList.forEach(ele => {
              let firstIndex = this.dataList.findIndex(item => {
                return item.receiptId === ele.receiptId   // 当receiptId相同的时候，返回第一个相同的Index 赋值给 firstIndex
              })
              if (arr.findIndex(item => {
                return item.firstIndex === firstIndex
              }) === -1) {
                arr.push({
                  length: this.dataList.filter(item => {
                    return item.receiptId === ele.receiptId    // 利用数组的filter方法，过滤出相同receiptId的数组的长度。数组长度-即为跨多少行
                  }).length,
                  firstIndex: firstIndex    // firstIndex 返回的是第一个receiptId就满足的第一个Index,即为rowIndex开始于第几行。
                })
              }
            })
            // arr = new Set(arr)
            // console.log(arr)
            this.indexInfoList = arr   // 得到的arr里面的内容：Array(3) // 0 : firstIndex : 0; length: 4  1: firstIndex: 4 length:5
            console.log(arr)

            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 导出
      _export () {
        this.$http({
          url: this.$http.adornUrl('/funds/clientreportdetailvo/export'),
          method: 'post',
          responseType: 'blob',
          params: this.$http.adornParams({
            'key': this.dataForm.key,
            'beginDate': this.dataForm.dateRange === null ? '' : this.dataForm.dateRange[0],
            'endDate': this.dataForm.dateRange === null ? '' : this.dataForm.dateRange[1]
          })
        }).then((response) => {
          let blob = new Blob([response.data], {type: 'application/vnd.ms-excel'})
          if (window.navigator.msSaveOrOpenBlob) {
              // 如果需要改名字，前台可以自动生成
            navigator.msSaveBlob(blob, '客户对账单')
          } else {
            let link = document.createElement('a')
            let evt = document.createEvent('HTMLEvents')
            evt.initEvent('click', false, false)
            link.href = URL.createObjectURL(blob)
            link.download = '客户对账单'
            link.style.display = 'none'
            document.body.appendChild(link)
            link.click()
            window.URL.revokeObjectURL(link.href)
          }
        }).catch((e) => { console.log(e) })
      },
      arraySpanMethod ({ row, column, rowIndex, columnIndex }) {
        if (columnIndex >= 0 && columnIndex < 5) {
          let index = this.indexInfoList.findIndex(item => {  // 遍历数组
            return item.firstIndex === rowIndex
          })
          if (index > -1) {
            return {
              rowspan: this.indexInfoList[index].length,
              colspan: 1
            }
          } else {
            return {
              rowspan: 0,
              colspan: 0
            }
          }
        }
      },
      indexMethod (index) {
        return index + 1
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 合计
      getSummaries (param) {
        const {columns, data} = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '合计'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          // 本次核销金额(元)
          if (column.property === 'thisWrittenOffAmount') {
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              sums[index] += ''
            } else {
              sums[index] = ''
            }

            sums[index] = parseFloat(sums[index]).toFixed(2)

            this.thisWrittenOffAmount = sums[index]
          }

          // 收款金额(元)
          if (column.property === 'receiptAmount') {
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              sums[index] += ''
            } else {
              sums[index] = ''
            }

            sums[index] = parseFloat(sums[index]).toFixed(2)

            this.receiptAmount = sums[index]
          }

          // 剩余金额(元)
          if (column.property === 'remainAmount') {
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              sums[index] += ''
            } else {
              sums[index] = ''
            }

            sums[index] = parseFloat(sums[index]).toFixed(2)

            this.remainAmount = sums[index]
          }
        })

        return sums
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/funds/clientreportdetailvo/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      // 打印页面内容
      printContent () {
        console.log(11)
        let wpt = document.querySelector('#clientReportDetailTable')
        let newContent = wpt.innerHTML
        let oldContent = document.body.innerHTML

        document.body.innerHTML = newContent
        window.print() // 打印方法
        // window.localtion.reload();
        history.go(0)
        document.body.innerHTML = oldContent
      },
      handleCheckAllChange (val) {
        this.checkedDetails = val ? reportDetails : []
        this.isIndeterminate = false
      },
      handleCheckedCitiesChange (value) {
        let checkedCount = value.length
        this.checkAll = checkedCount === this.reportDetails.length
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.reportDetails.length
      },
      handleTitle () {
        this.titleList = ''
        this.keyList = ''

        for (let i = 0, leng = this.checkedDetails.length; i < leng; i++) {
          let title = this.checkedDetails[i]

          let key = alertReportDetailName[title]

          if (i !== leng - 1) {
            this.titleList += title + ','

            this.keyList += key + ','
          } else {
            this.titleList += title

            this.keyList += key
          }
        }

        this.clientReportVisible = false
      },
      _exportCSV () {
        this.$http({
          url: this.$http.adornUrl('/funds/clientreportdetailvo/exportCSV'),
          method: 'post',
          responseType: 'blob',
          params: this.$http.adornParams({
            'titles': this.titleList,
            'keys': this.keyList,
            'beginDate': this.dataForm.dateRange === null ? '' : this.dataForm.dateRange[0],
            'endDate': this.dataForm.dateRange === null ? '' : this.dataForm.dateRange[1]
          })
        }).then((response) => {
          if (response) {
            let url = window.URL.createObjectURL(new Blob([response.data], {type: 'application/ms-txt.numberformat:@'}))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', '客户对账单.csv')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          } else {
            this.$message.error('请设置要导出的字段')
          }
        })
      }
    }
  }
</script>
